package com.seasugar.raggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seasugar.raggie.common.BaseContext;
import com.seasugar.raggie.common.R;
import com.seasugar.raggie.model.entity.User;
import com.seasugar.raggie.service.UserService;
import com.seasugar.raggie.utils.EmailUtil;
import com.seasugar.raggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("sendMsg")
    //和前端名字相同却接收不到，取不到的原因：前端给的是一个对象
    public R sendMsg(@RequestBody User user) throws Exception {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
//            session.setAttribute(phone, code);
            //将生成的验证码存入redis并设置过期时间
            //key设置前缀便于后期管理
            phone="email:"+phone;
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            //邮箱发送
            String email=phone.substring(phone.lastIndexOf(":")+1);
            log.info(email);
            EmailUtil.transfer(email,code);
            return R.success("发送成功");
        }
        return R.error("发送失败");
    }

    @PostMapping("login")
    //这里没有新建DTO获取对象，而是使用了Map接收一切key value
    public R login(@RequestBody Map map,HttpSession session) {
        String phone = "email:"+(String) map.get("phone");
        String code = (String) map.get("code");
        log.info(phone);
        log.info(code);
//        String code1 = (String) session.getAttribute(phone);
        //从redis获取验证码
        String code1 = (String) redisTemplate.opsForValue().get(phone);
        //如果HttpSession中存了这个手机的验证码才进行判断
        if (StringUtils.isNotEmpty(code1)) {
            if (code1.equals(code)) {
                //由于手机的唯一性，所以可以用phone获取唯一用户
                LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getPhone,phone);
                User user = userService.getOne(queryWrapper);
                if(user==null){
                    //新用户，直接注册
                    user=new User();
                    user.setPhone(phone);
                    userService.save(user);
                }
                session.setAttribute("user",user);
                //登陆成功后删除redis缓存的验证码
                redisTemplate.delete(phone);
                return R.success("登录成功");
            }
            else
                return R.error("验证码错误");
        }
        return R.error("未发送验证码或验证码过期");
    }

    @PostMapping("loginout")
    public R loginout(HttpSession session){
        //清除session
        session.removeAttribute("user");
        BaseContext.removeCurrentId();
        return R.success("退出成功");
    }
}
